package org.zjx.core;

import com.sun.jna.platform.win32.WinDef;
import lombok.Getter;
import lombok.Setter;
import lombok.SneakyThrows;
import org.zjx.listener.EventListener;
import org.zjx.task.core.ITaskChain;
import org.zjx.task.core.TaskScheduler;
import org.zjx.util.HwndUtil;
import org.zjx.window.GameWindow;
import org.zjx.window.GameWindowManager;
import org.zjx.window.WindowResource;

import java.awt.*;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

@Getter
@Setter
public class GameThread implements Runnable {
    private final String threadId; // 唯一线程标识
    private WinDef.HWND hwnd = null;
    private GameWindow window;
    private TaskManager taskManager;
    private GameContext gameContext;

    private boolean running = true;
    private AtomicBoolean needAssistant = new AtomicBoolean(false);

    private EventListener eventListener = o -> {
        if (!TaskScheduler.NO_TASK_VALUE.equals(o)) return;
        needAssistant.set(true);
    };


    public GameThread(String threadId) {
        this.threadId = threadId;
        gameContext = new GameContext();
        gameContext.addListener(TaskScheduler.class.getSimpleName(), eventListener);
        new GameInstance.Builder().gameContext(gameContext).gameThread(this).build();
        this.taskManager = new TaskManager(GameInstance.getInstance());
    }

    @SneakyThrows
    @Override
    public void run() {
        System.out.println("[" + threadId + "] 线程开始运行");
        try {
            while (running) {
                if (!HwndUtil.haveHwnd(hwnd)) {
                    running = false;
                } else {
                    assistant();
                }
            }
        } finally {
            // 释放窗口资源
            GameWindowManager.getInstance().releaseResource(hwnd);
            taskManager.shutdown();
            System.out.println("[" + threadId + "] 线程正常结束");
        }
    }

    public void assistant() {
        if (!needAssistant.get()) return;
        List<ITaskChain> chains = taskManager.getChains("chain/chain-main.txt");
        taskManager.add(chains);
        needAssistant.set(false);
    }

    public void initialize() {
        System.out.println("[" + threadId + "] 初始化中...");

        WindowResource windowResource = GameWindowManager.getInstance().acquireResource();
        this.hwnd = windowResource.getHwnd();
        window = new GameWindow(new Point(windowResource.getRect().getLeft(),windowResource.getRect().getTop()));
        window.init(windowResource.getHwnd(),GameWindow.WINDOW_STATUS_LOGIN);
    }
}
